package resources

import (
	"testing"
	"time"

	"github.com/stackrox/rox/generated/internalapi/central"
	"github.com/stackrox/rox/generated/storage"
	"github.com/stackrox/rox/pkg/docker/config"
	"github.com/stackrox/rox/pkg/protoassert"
	"github.com/stackrox/rox/pkg/protocompat"
	"github.com/stackrox/rox/sensor/common/awscredentials"
	"github.com/stackrox/rox/sensor/common/awscredentials/mocks"
	"github.com/stretchr/testify/assert"
	"go.uber.org/mock/gomock"
)

func Test_deploymentHandler_getImageIntegrationEvent(t *testing.T) {
	tests := []struct {
		name        string
		want        *central.SensorEvent
		credentials *awscredentials.RegistryCredentials
	}{
		{
			name: "when no credentials, then no event",
		},
		{
			name: "when valid credentials, then expected event",
			credentials: &awscredentials.RegistryCredentials{
				AWSAccount: "123456",
				AWSRegion:  "foo-bar-1",
				DockerConfig: &config.DockerConfigEntry{
					Username: "fooz",
					Password: "barz",
				},
				ExpirestAt: time.UnixMilli(0),
			},
			want: &central.SensorEvent{
				Action: central.ResourceAction_UPDATE_RESOURCE,
				Resource: &central.SensorEvent_ImageIntegration{
					ImageIntegration: &storage.ImageIntegration{
						Type: "ecr",
						IntegrationConfig: &storage.ImageIntegration_Ecr{
							Ecr: &storage.ECRConfig{
								Region:     "foo-bar-1",
								RegistryId: "123456",
								AuthorizationData: &storage.ECRConfig_AuthorizationData{
									ExpiresAt: protocompat.GetProtoTimestampZero(),
									Username:  "fooz",
									Password:  "barz",
								},
							},
						},
						Autogenerated: true,
					},
				},
			},
		},
	}
	ctrl := gomock.NewController(t)
	registry := "foobar-registry.com"
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			m := mocks.NewMockRegistryCredentialsManager(ctrl)
			d := &deploymentHandler{
				credentialsManager: m,
			}
			m.EXPECT().GetRegistryCredentials(gomock.Eq(registry)).Return(tt.credentials).Times(1)
			ret := d.getImageIntegrationEvent(registry)
			if tt.want == nil {
				assert.Nil(t, ret)
			} else {
				i := ret.GetImageIntegration()
				assert.Equal(t, tt.want.GetAction(), ret.GetAction())
				assert.IsType(t, (*storage.ImageIntegration_Ecr)(nil), i.GetIntegrationConfig())
				protoassert.Equal(t, tt.want.GetImageIntegration().GetEcr(), i.GetEcr())
				assert.True(t, i.GetAutogenerated())
			}
		})
	}
}
